import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;
import java.sql.*;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;

public class ConferenceReservationSystem {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MainFrame mainFrame = new MainFrame();
            mainFrame.setVisible(true);
        });
    }
}

class MainFrame extends JFrame {
    private final MeetingService meetingService;
    private final DefaultTableModel meetingTableModel;

    public MainFrame() {
        meetingService = new MeetingService();

        setTitle("智能会议室预订系统");
        setSize(1200, 800);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new BorderLayout());

        // 顶部工具栏
        JToolBar toolBar = new JToolBar();
        JButton newReservationBtn = new JButton("新建预订");
        newReservationBtn.addActionListener(e -> openReservationDialog());
        toolBar.add(newReservationBtn);
        mainPanel.add(toolBar, BorderLayout.NORTH);

        // 会议列表
        String[] columns = {"会议ID", "会议名称", "主持人", "开始时间", "会议室", "状态", "操作"};
        meetingTableModel = new DefaultTableModel(columns, 0);
        JTable meetingTable = new JTable(meetingTableModel) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        JScrollPane scrollPane = new JScrollPane(meetingTable);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 初始化会议数据
        refreshMeetingList();

        add(mainPanel);
    }

    private void openReservationDialog() {
        ReservationDialog dialog = new ReservationDialog(this, meetingService);
        dialog.setVisible(true);
        refreshMeetingList();
    }

    private void refreshMeetingList() {
        meetingTableModel.setRowCount(0);
        List<Meeting> meetings = meetingService.getAllMeetings();
        for (Meeting m : meetings) {
            Object[] row = {
                    m.getMid(),
                    m.getMname(),
                    m.getName(),
                    m.getMtime(),
                    m.getRoomNumber(),
                    m.getStatus(),
                    "<html><a href=''>查看详情</a></html>"
            };
            meetingTableModel.addRow(row);
        }
    }
}

class ReservationDialog extends JDialog {
    private final MeetingService meetingService;

    public ReservationDialog(Frame owner, MeetingService service) {
        super(owner, "新建会议预订", true);
        this.meetingService = service;
        initUI();
    }

    private void initUI() {
        setLayout(new MigLayout("wrap 2", "[grow][grow]", "[]10[]10[]10[]10[]20[]"));

        // 表单组件
        JTextField meetingNameField = new JTextField();
        JComboBox<String> meetingTypeCombo = new JComboBox<>(new String[]{"内部会议", "客户会议", "培训"});
        JSpinner startTimeSpinner = new JSpinner(new SpinnerDateModel());
        JSpinner durationSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 8, 1));
        JComboBox<MeetingRoom> roomCombo = new JComboBox<>(MeetingService.loadAvailableRooms().toArray(new MeetingRoom[0]));

        // 添加组件
        add(new JLabel("会议名称:"), "cell 0 0");
        add(meetingNameField, "cell 1 0, growx");
        add(new JLabel("会议类型:"), "cell 0 1");
        add(meetingTypeCombo, "cell 1 1, growx");
        add(new JLabel("开始时间:"), "cell 0 2");
        add(startTimeSpinner, "cell 1 2, growx");
        add(new JLabel("持续时间(小时):"), "cell 0 3");
        add(durationSpinner, "cell 1 3, growx");
        add(new JLabel("选择会议室:"), "cell 0 4");
        add(roomCombo, "cell 1 4, growx");

        // 按钮
        JButton confirmBtn = new JButton("确认预订");
        JButton cancelBtn = new JButton("取消");
        add(confirmBtn, "cell 0 5, split 2");
        add(cancelBtn, "cell 1 5");

        // 事件处理
        confirmBtn.addActionListener(e -> {
            if (validateForm(meetingNameField, startTimeSpinner, durationSpinner, roomCombo)) {
                MeetingRequest request = new MeetingRequest(
                        meetingNameField.getText(),
                        (String) meetingTypeCombo.getSelectedItem(),
                        (Date) startTimeSpinner.getValue(),
                        (Integer) durationSpinner.getValue(),
                        (MeetingRoom) roomCombo.getSelectedItem()
                );

                try {
                    meetingService.submitReservation(request);
                    JOptionPane.showMessageDialog(this, "预订成功！会议ID：" + request.getMeetingId());
                    dispose();
                } catch (ReservationConflictException ex) {
                    JOptionPane.showMessageDialog(this,
                            "预订失败：" + ex.getMessage(),
                            "冲突错误",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        cancelBtn.addActionListener(e -> dispose());

        pack();
        setLocationRelativeTo(getOwner());
    }

    private boolean validateForm(JTextField nameField,
                                 JSpinner timeSpinner,
                                 JSpinner durationSpinner,
                                 JComboBox<MeetingRoom> roomCombo) {
        if (nameField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "会议名称不能为空");
            return false;
        }

        Date startTime = (Date) timeSpinner.getValue();
        if (startTime.before(new Date())) {
            JOptionPane.showMessageDialog(this, "开始时间不能早于当前时间");
            return false;
        }

        if (roomCombo.getSelectedItem() == null) {
            JOptionPane.showMessageDialog(this, "请选择会议室");
            return false;
        }

        return true;
    }
}

class MeetingService {
    private final MeetingDAO meetingDAO = new MeetingDAO();

    public void submitReservation(MeetingRequest request) throws ReservationConflictException {
        MeetingRoom selectedRoom = request.getRoom();
        Date startTime = request.getStartTime();
        int duration = request.getDuration();
        Date endTime = new Date(startTime.getTime() + duration * 3600_000L);

        List<Meeting> conflicts = meetingDAO.checkConflicts(
                selectedRoom.getId(), startTime, endTime);

        if (!conflicts.isEmpty()) {
            throw new ReservationConflictException(
                    "会议室已被预订：" + conflicts.get(0).getMname());
        }

        Meeting meeting = new Meeting();
        meeting.setMid(generateMID());
        meeting.setMname(request.getMeetingName());
        meeting.setName(request.getHostName());
        meeting.setMtime(request.getStartTime());
        meeting.setPlace(selectedRoom.getLocation());
        meeting.setLocation(selectedRoom.getName());
        meeting.setRoomNumber(selectedRoom.getRoomNumber());
        meeting.setForm("线下会议");
        meeting.setType(request.getType());
        meeting.setStatus("已预订");

        meetingDAO.addMeeting(meeting);
        request.setMeetingId(meeting.getMid());
    }

    public List<Meeting> getAllMeetings() {
        return meetingDAO.getAllMeetings();
    }

    public static List<MeetingRoom> loadAvailableRooms() {
        return List.of(
                new MeetingRoom(1, "第一会议室", "A座301", "301", 20),
                new MeetingRoom(2, "第二会议室", "B座205", "205", 15),
                new MeetingRoom(3, "报告厅", "C座1层", "101", 100)
        );
    }

    private String generateMID() {
        return "MID" + System.currentTimeMillis();
    }
}

class MeetingDAO {
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL =
            "jdbc:mysql://sh-cdb-l52i6pgu.sql.tencentcdb.com:29750/schoolmeeting?useSSL=false";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "745698Mjt123";

    public MeetingDAO() {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("MySQL JDBC驱动未找到", e);
        }
    }

    public boolean addMeeting(Meeting meeting) {
        String sql = "INSERT INTO meeting " +
                "(MID, Mname, Name, Mtime, Place, Location, Room, Form, Type, Status) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, meeting.getMid());
            pstmt.setString(2, meeting.getMname());
            pstmt.setString(3, meeting.getName());
            pstmt.setTimestamp(4, new Timestamp(meeting.getMtime().getTime()));
            pstmt.setString(5, meeting.getPlace());
            pstmt.setString(6, meeting.getLocation());
            pstmt.setString(7, meeting.getRoomNumber());
            pstmt.setString(8, meeting.getForm());
            pstmt.setString(9, meeting.getType());
            pstmt.setString(10, meeting.getStatus());

            return pstmt.executeUpdate() > 0;

        } catch (SQLException e) {
            throw new RuntimeException("数据库操作失败", e);
        }
    }

    public List<Meeting> checkConflicts(int roomId, Date start, Date end) {
        List<Meeting> conflicts = new ArrayList<>();
        // 此处应实现实际的数据库查询
        SELECT * FROM meeting WHERE Room = ? AND
        ((Mtime <= ? AND ? < DATE_ADD(Mtime, INTERVAL Duration HOUR)) OR (DATE_ADD(Mtime, INTERVAL Duration HOUR) > ? AND Mtime < ?))
        return conflicts;
    }

    public List<Meeting> getAllMeetings() {
        List<Meeting> meetings = new ArrayList<>();
        // 此处应实现实际的数据库查询
        SELECT * FROM meeting ORDER BY Mtime DESC
        return meetings;
    }
}

class Meeting {
    private String mid;
    private String mname;
    private String name;
    private Date mtime;
    private String place;
    private String location;
    private String roomNumber;
    private String form;
    private String type;
    private String status;

    public String getMid() {
        return mid;
    }

    public void setMid(String mid) {
        this.mid = mid;
    }

    public String getMname() {
        return mname;
    }

    public void setMname(String mname) {
        this.mname = mname;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getMtime() {
        return mtime;
    }

    public void setMtime(Date mtime) {
        this.mtime = mtime;
    }

    public String getPlace() {
        return place;
    }

    public void setPlace(String place) {
        this.place = place;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getRoomNumber() {
        return roomNumber;
    }

    public void setRoomNumber(String roomNumber) {
        this.roomNumber = roomNumber;
    }

    public String getForm() {
        return form;
    }

    public void setForm(String form) {
        this.form = form;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
// Getters and Setters
    // ...（需要完整实现所有字段的getter/setter）
}

class MeetingRequest {
    private String meetingId;
    private final String meetingName;
    private final String hostName;
    private final Date startTime;
    private final int duration;
    private final MeetingRoom room;
    private final String type;

    public MeetingRequest(String meetingName, String type, Date startTime,
                          int duration, MeetingRoom room) {
        this.meetingName = meetingName;
        this.type = type;
        this.startTime = startTime;
        this.duration = duration;
        this.room = room;
        this.hostName = "当前用户"; // 需要集成用户系统
    }

    // Getters
    public String getMeetingId() { return meetingId; }
    public void setMeetingId(String meetingId) { this.meetingId = meetingId; }
    public String getMeetingName() { return meetingName; }
    public String getType() { return type; }
    public Date getStartTime() { return startTime; }
    public int getDuration() { return duration; }
    public MeetingRoom getRoom() { return room; }
    public String getHostName() { return hostName; }
}

class MeetingRoom {
    private final int id;
    private final String name;
    private final String location;
    private final String roomNumber;
    private final int capacity;

    public MeetingRoom(int id, String name, String location, String roomNumber, int capacity) {
        this.id = id;
        this.name = name;
        this.location = location;
        this.roomNumber = roomNumber;
        this.capacity = capacity;
    }

    // Getters
    public int getId() { return id; }
    public String getName() { return name; }
    public String getLocation() { return location; }
    public String getRoomNumber() { return roomNumber; }
    public int getCapacity() { return capacity; }
}

class ReservationConflictException extends Exception {
    public ReservationConflictException(String message) {
        super(message);
    }
}